﻿using BleSolution;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;

namespace YH.Bluetooth
{
    public partial class Form6 : Form
    {
        private readonly IWebSocketServerService _webSocketServerService;
        private Task _serverTask2;

        /// <summary>
        /// 蓝牙处理核心类
        /// </summary>
        BleCoreNew bleCore = null;
        /// <summary>
        /// 存储检测到的设备
        /// </summary>
        List<Windows.Devices.Bluetooth.BluetoothLEDevice> DeviceList = new List<Windows.Devices.Bluetooth.BluetoothLEDevice>();
        /// <summary>
        /// 当前蓝牙服务列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService> GattDeviceServices = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService>();
        /// <summary>
        /// 当前蓝牙服务特征列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic> GattCharacteristics = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic>();


        public Form6(IWebSocketServerService webSocketServerService)
        {
            try
            {
                InitializeComponent();
                _webSocketServerService = webSocketServerService;

                _webSocketServerService.DeviceFindChanged += websocket_DeviceFindChanged;


                bleCore = new BleCoreNew(_webSocketServerService);

                CheckForIllegalCrossThreadCalls = false;
                this.bleCore.MessAgeChanged += BleCore_MessAgeChanged;
                this.bleCore.DeviceWatcherChanged += BleCore_DeviceWatcherChanged;
                this.bleCore.GattDeviceServiceAdded += BleCore_GattDeviceServiceAdded;
                this.bleCore.CharacteristicAdded += BleCore_CharacteristicAdded;
                LogHelper.WriteLog("程序启动");
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 异步线程
        /// </summary>
        /// <param name="action"></param>
        public static void RunAsync(Action action)
        {
            try
            {
                ((Action)(delegate ()
                {
                    action.Invoke();
                })).BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        private void BleCore_MessAgeChanged(BleSolution.MsgType type, string message, byte[] data)
        {
            try
            {

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <param name="bluetoothLEDevice"></param>
        private void BleCore_DeviceWatcherChanged(BleSolution.MsgType type, BluetoothLEDevice bluetoothLEDevice)
        {
            try
            {
                RunAsync(() =>
                {
                    this.DeviceList.Add(bluetoothLEDevice);

                    string my_name = bluetoothLEDevice.Name;
                    byte[] _Bytes1 = BitConverter.GetBytes(bluetoothLEDevice.BluetoothAddress);
                    Array.Reverse(_Bytes1);
                    string my_mac = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                    SendFindReplyDevicesubClass my_sendFindReplyDevicesubClass = new SendFindReplyDevicesubClass();
                    my_sendFindReplyDevicesubClass.name = my_name;
                    my_sendFindReplyDevicesubClass.mac = my_mac;
                    SendFindReplyDeviceClass my_sendFindReplyDeviceClass = new SendFindReplyDeviceClass();
                    my_sendFindReplyDeviceClass.command = CommondCode.find_device_reply.ToString();
                    my_sendFindReplyDeviceClass.device = my_sendFindReplyDevicesubClass;
                    string my_send_data = JsonConvert.SerializeObject(my_sendFindReplyDeviceClass);
                    // Thread.Sleep(100);
                    _webSocketServerService.SendMessageToAllAsync(my_send_data);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }

        }

        private void BleCore_GattDeviceServiceAdded(GattDeviceService gattDeviceService)
        {
            throw new NotImplementedException();
        }

        private void BleCore_CharacteristicAdded(GattCharacteristic gattCharacteristic)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 功能：收到客户端通知搜索设备
        /// </summary>
        /// <param name="message"></param>
        private void websocket_DeviceFindChanged(string message)
        {
            try
            {
                LogHelper.WriteLog("停止蓝牙设备");
                this.bleCore.StopBleDeviceWatcher();
                Thread.Sleep(2000);

                LogHelper.WriteLog("搜索蓝牙设备");
                this.bleCore.StartBleDeviceWatcher();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }

        private void btn_open_service_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击启动服务器按钮");
                if (_serverTask2 == null || _serverTask2.IsCompleted)
                {
                    _serverTask2 = _webSocketServerService.StartAsync();
                   // MessageBox.Show("WebSocket 服务器正在启动...");
                    LogHelper.WriteLog("WebSocket 服务器正在启动...");
                }
                else
                {
                    MessageBox.Show("WebSocket 服务器已经在运行！");
                    LogHelper.WriteLog("WebSocket 服务器已经在运行...");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
    }
}
